package com.cheung.leetcode.arr;

import org.junit.jupiter.api.Test;

import java.util.Arrays;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.arr
 * @Author :  cheungming
 * @CreateTime : 2024-08-16 19:23:16
 * @Description : 16
 * @Version : 1.0
 */
public class Code16Test {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;

        // 初始化 res
        int res = nums[0] + nums[1] + nums[2];
        for (int first = 0; first < nums.length; first++) {
            int second = first + 1;
            int third = n - 1;
            while (second < third) {
                int sum = nums[first] + nums[second] + nums[third];
                if (sum == target) {
                    return sum;
                }

                // 如果 sum 满足条件，则更新 res
                if (Math.abs(sum - target) < Math.abs(res - target)) {
                    res = sum;
                }

                if (sum > target) {
                    third--;
                } else {
                    second++;
                }
            }
        }

        return res;
    }

    @Test
    public void test1() {
        assert threeSumClosest(new int[]{-1, 2, 1, -4}, 1) == 2;
    }

    @Test
    public void test2() {
        assert threeSumClosest(new int[]{0, 0, 0}, 1) == 0;
    }
}
